package com.company;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端处理线程
 */
public class SocketClientChannelThread implements Runnable {
  private SocketChannel clientChannel;             //客户端通道
  private boolean flag = true;                       //循环标记

  public SocketClientChannelThread(SocketChannel clientChannel) throws Exception {
    this.clientChannel = clientChannel;              //保存客户端通道
    System.out.println("【客户端连接成功】，该客户端的地址为：" + clientChannel.getRemoteAddress());

  }

  /**
   * 线程任务
   */

  @Override
  public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(50);            //创建缓冲区
    try {
      while (this.flag) {
        //可能会重复使用一个buffer，所以是使用之前做清空处理
        buffer.clear();
        int readCount = this.clientChannel.read(buffer);     //接收客户端发送数据
        String readMessage = new String(buffer.array(), 0, readCount).trim();
        System.out.println("【服务器接收到消息】" + readMessage);
        String writeMessage = "【echo】" + readMessage + "\n";
        if ("exit".equals(readMessage)) {
          writeMessage = "【exit】拜拜，下次再见";
          this.flag = false;                     //修改标记
        }
        buffer.clear();
        buffer.put(writeMessage.getBytes()); //缓冲区保存数据
        buffer.flip();                       //重置缓冲区
        this.clientChannel.write(buffer);    //回应信息
      }
      this.clientChannel.close();           //关闭通道
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


